﻿using AntUnion.FrameWork.Model.Models;
using Microsoft.CodeAnalysis;
using Microsoft.EntityFrameworkCore;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Linq;

namespace AntUnion.FrameWork.Web.Service
{
    public class ReferralService
    {
        /// <summary>
        /// 获取我的二级下线
        /// </summary>
        /// <param name="mtContext"></param>
        /// <param name="crmId"></param>
        /// <returns></returns>
        public void GetClients(int crmId, out int oneClients, out int towClients)
        {
            try
            {
                using (mtContext mtContext = new mtContext())
                {
                    List<int> oneCrmId = mtContext.CrmUsers.Where(k => k.CrmUp == crmId).Select(k => k.Id).ToList();
                    List<int> twoCrmId = mtContext.CrmUsers.Where(k => oneCrmId.Contains((int)k.CrmUp)).Select(k => k.Id).ToList();
                    oneClients = oneCrmId.Count;
                    towClients = twoCrmId.Count;
                }
            }
            catch (Exception)
            {

                throw;
            }
        }

        public Promotion GetApplication(int crmId)
        {
            try
            {
                using (mtContext mtContext = new mtContext())
                {
                    //如果审核中或者通过，则不能再提交
                    return mtContext.Promotions.OrderByDescending(k => k.Id).FirstOrDefault(k => k.CrmId == crmId);
                }
            }
            catch (System.Exception)
            {

                throw;
            }
        }

        public int SendApplication(int crmId, string cont)
        {
            try
            {
                using (mtContext mtContext = new mtContext())
                {
                    Promotion promotion = new Promotion();
                    promotion.CrmId = crmId;
                    promotion.Cont = cont;
                    promotion.CreateDate = DateTime.Now;
                    promotion.State = 0;
                    mtContext.Promotions.Add(promotion);
                    return mtContext.SaveChanges();
                }
            }
            catch (System.Exception)
            {

                throw;
            }
        }

        #region 个人返佣报表

        public class PersonReportModel
        {
            public int id { get; set; }
            public int owner { get; set; }
            public string ownerFullName { get; set; }
            public int crmId { get; set; }
            public long tradingAccount { get; set; }
            public string CRMAccount { get; set; }
            public string name { get; set; }
            public uint? accountGroup { get; set; }
            public string programme { get; set; }
            public string rebateLevel { get; set; }
            public decimal cardinal { get; set; }
            public string rebateAmount { get; set; }
            public DateTime rebateTime { get; set; }
            public DateTime balanceDate { get; set; }
        }

        public List<PersonReportModel> PersonReport(int page, int limit, int crmId, string alllName, string rebateTime, string balanceDate, out int count)
        {
            try
            {
                using (mtContext mtContext = new mtContext())
                {
                    var data = from y in mtContext.PersonReports.Where(k => k.Owner == crmId)
                               join c in mtContext.CrmUsers on y.Crmid equals c.Id
                               //join s in mtContext.RebateSchemes on y.SchemeId equals s.Id
                               //join l in mtContext.RebateLevels on y.LevelId equals l.Id
                               select new PersonReportModel
                               {
                                   id = y.Id,
                                   crmId = y.Crmid,
                                   tradingAccount = y.Mt5login,
                                   CRMAccount = c.LoginName,
                                   name = c.Name,
                                   //ownerFullName = string.Format("{0}/{1}/{2}", y.Mt5login, c.LoginName, c.Name),
                                   accountGroup = c.CrmGroup,
                                   programme = y.Scheme,//mtContext.RebateSchemes.FirstOrDefault(k => k.Id == y.SchemeId) == null ? "" : mtContext.RebateSchemes.FirstOrDefault(k => k.Id == y.SchemeId).Names,
                                   rebateLevel = y.Level,//mtContext.RebateLevels.FirstOrDefault(k => k.Level == y.LevelId && k.Pid == 0) == null ? "" : mtContext.RebateLevels.FirstOrDefault(k => k.Level == y.LevelId && k.Pid == 0).Names,
                                   cardinal = y.Coefficient,
                                   rebateAmount = y.Money.ToString("#,##0.00"),
                                   rebateTime = y.Addtime,
                                   balanceDate = y.Date
                               };
                    if (!string.IsNullOrEmpty(alllName))
                    {
                        //data = data.Where(k => k.ownerFullName.Contains(fullName));
                        data = data.Where(k => (k.tradingAccount + "/" + k.CRMAccount + "/" + k.name).Contains(alllName));
                    }
                    if (!string.IsNullOrEmpty(rebateTime) && rebateTime.Contains(" - "))
                    {
                        string[] registrationTimes = rebateTime.Split(new string[] { " - " }, StringSplitOptions.None);
                        DateTime startTime = Convert.ToDateTime(registrationTimes[0]);
                        DateTime endTime = Convert.ToDateTime(registrationTimes[1]);
                        data = data.Where(k => k.rebateTime > startTime && k.rebateTime < endTime);
                    }
                    if (!string.IsNullOrEmpty(balanceDate))
                    {
                        DateTime balanceTime = Convert.ToDateTime(balanceDate);
                        data = data.Where(k => k.balanceDate == balanceTime);
                    }
                    if (page == 0 && limit == 0)
                    {
                        data = data.OrderByDescending(k => k.id);
                    }
                    else
                    {
                        data = data.OrderByDescending(k => k.id).Skip((page - 1) * limit).Take(limit);
                    }
                    count = data.Count();
                    return data.ToList();
                }
            }
            catch (System.Exception)
            {

                throw;
            }
        }

        #endregion

        #region 返佣明细

        public List<string> CommissionDetailedReportSymbol()
        {
            try
            {
                using (mtContext mtContext = new mtContext())
                {
                    var data = mtContext.CommissionDetailedReports.OrderBy(k => k.Symbol).Select(k => k.Symbol).Distinct().ToList();
                    return data;
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        public class DailyDetailedReportModel
        {
            public int id { get; set; }
            public int owner { get; set; }
            public string ownerFullName { get; set; }
            public int crmId { get; set; }
            public long tradingAccount { get; set; }
            public string CRMAccount { get; set; }
            public string name { get; set; }
            public uint? accountGroup { get; set; }
            public string deal { get; set; }
            public string symbol { get; set; }
            public long volume { get; set; }
            public string programme { get; set; }
            public string rebateLevel { get; set; }
            public string cardinal { get; set; }
            public string rebateAmount { get; set; }
            public DateTime rebateTime { get; set; }
            public DateTime balanceDate { get; set; }
        }

        public List<DailyDetailedReportModel> DailyDetailedReport(int page, int limit, int crmId, string alllName, string symbol, string rebateTime, string balanceDate, out int count)
        {
            try
            {
                using (mtContext mtContext = new mtContext())
                {
                    var data = from y in mtContext.CommissionDetailedReports.Where(k => k.Owner == crmId)
                               join c in mtContext.CrmUsers on y.Crmid equals c.Id
                               //join s in mtContext.RebateSchemes on y.SchemeId equals s.Id
                               select new DailyDetailedReportModel
                               {
                                   id = y.Id,
                                   crmId = y.Crmid,
                                   tradingAccount = y.Mt5login,
                                   CRMAccount = c.LoginName,
                                   name = c.Name,
                                   //ownerFullName = string.Format("{0}/{1}/{2}", y.Mt5login, c.LoginName, c.Name),
                                   accountGroup = c.CrmGroup,
                                   deal = y.Deal.ToString(),
                                   symbol = y.Symbol,
                                   volume = y.Volume,
                                   programme = y.Scheme, //mtContext.RebateSchemes.FirstOrDefault(k => k.Id == y.SchemeId) == null ? "" : mtContext.RebateSchemes.FirstOrDefault(k => k.Id == y.SchemeId).Names,
                                   rebateLevel = y.Level, //mtContext.RebateLevels.FirstOrDefault(k => k.Level == y.LevelId && k.Pid == 0) == null ? "" : mtContext.RebateLevels.FirstOrDefault(k => k.Level == y.LevelId && k.Pid == 0).Names,
                                   cardinal = y.Coefficient.ToString("#,##0.00"),
                                   rebateAmount = y.Money.ToString("#,##0.00"),
                                   rebateTime = y.Addtime,
                                   balanceDate = y.Date
                               };
                    if (!string.IsNullOrEmpty(alllName))
                    {
                        //data = data.Where(k => k.ownerFullName.Contains(fullName));
                        data = data.Where(k => (k.tradingAccount + "/" + k.CRMAccount + "/" + k.name).Contains(alllName));
                    }
                    if (!string.IsNullOrEmpty(symbol))
                    {
                        data = data.Where(k => k.symbol.Contains(symbol));
                    }
                    if (!string.IsNullOrEmpty(rebateTime) && rebateTime.Contains(" - "))
                    {
                        string[] registrationTimes = rebateTime.Split(new string[] { " - " }, StringSplitOptions.None);
                        DateTime startTime = Convert.ToDateTime(registrationTimes[0]);
                        DateTime endTime = Convert.ToDateTime(registrationTimes[1]);
                        data = data.Where(k => k.rebateTime > startTime && k.rebateTime < endTime);
                    }
                    if (!string.IsNullOrEmpty(balanceDate))
                    {
                        DateTime balanceTime = Convert.ToDateTime(balanceDate);
                        data = data.Where(k => k.balanceDate == balanceTime);
                    }
                    if (page == 0 && limit == 0)
                    {
                        data = data.OrderByDescending(k => k.id);
                    }
                    else
                    {
                        data = data.OrderByDescending(k => k.id).Skip((page - 1) * limit).Take(limit);
                    }
                    count = data.Count();
                    return data.ToList();
                }
            }
            catch (System.Exception)
            {

                throw;
            }
        }

        #endregion

        #region 我的下线

        public class LevelUserModel
        {
            public int crmId { get; set; }
            public string ownerFullName { get; set; }
            public string tradingAccountNo { get; set; }
            public string CRMAccount { get; set; }
            public int Level { get; set; }
            public int dealCount { get; set; }
            public DateTime registerTime { get; set; }
        }

        public List<LevelUserModel> GetLevelOneUser(int page, int limit, long crmId, string registerTime, out int count)
        {
            try
            {
                using (mtContext mtContext = new mtContext())
                {
                    var data = from crm in mtContext.CrmUsers.Where(k => k.CrmUp == crmId && k.Isdel == 0)
                               join mt5 in mtContext.Mt5Users on crm.Id equals mt5.CrmId into crmmt5
                               from crmmt5i in crmmt5.DefaultIfEmpty()
                               select new LevelUserModel
                               {
                                   crmId = crm.Id,
                                   ownerFullName = crm.Name,
                                   tradingAccountNo = crmmt5i == null ? "" : crmmt5i.Login.ToString(),
                                   CRMAccount = crm.LoginName,
                                   Level = 1,
                                   dealCount = crmmt5i == null ? 0 : mtContext.Mt5Deals.Where(k => k.Login == crmmt5i.Login).Count(),
                                   registerTime = crm.CreateDate
                               };
                    if (!string.IsNullOrEmpty(registerTime) && registerTime.Contains(" - "))
                    {
                        string[] registrationTimes = registerTime.Split(new string[] { " - " }, StringSplitOptions.None);
                        DateTime startTime = Convert.ToDateTime(registrationTimes[0]);
                        DateTime endTime = Convert.ToDateTime(registrationTimes[1]);
                        data = data.Where(k => k.registerTime > startTime && k.registerTime < endTime);
                    }
                    count = data.Count();
                    data = data.OrderByDescending(k => k.registerTime).Skip((page - 1) * limit).Take(limit);
                    return data.ToList();
                }
            }
            catch (System.Exception)
            {

                throw;
            }
        }

        public List<LevelUserModel> GetLevelTwoUser(int page, int limit, long crmId, string registerTime, out int count)
        {
            try
            {
                using (mtContext mtContext = new mtContext())
                {
                    List<int> level1User = mtContext.CrmUsers.Where(k => k.CrmUp == crmId && k.Isdel == 0).Select(k => k.Id).ToList();
                    var data = from crm in mtContext.CrmUsers.Where(k => level1User.Contains((int)k.CrmUp) && k.Isdel == 0)
                               join mt5 in mtContext.Mt5Users on crm.Id equals mt5.CrmId into crmmt5
                               from crmmt5i in crmmt5.DefaultIfEmpty()
                               select new LevelUserModel
                               {
                                   crmId = crm.Id,
                                   ownerFullName = crm.Name,
                                   tradingAccountNo = crmmt5i == null ? "" : crmmt5i.Login.ToString(),
                                   CRMAccount = crm.LoginName,
                                   Level = 2,
                                   dealCount = crmmt5i == null ? 0 : mtContext.Mt5Deals.Where(k => k.Login == crmmt5i.Login).Count(),
                                   registerTime = crm.CreateDate
                               };
                    if (!string.IsNullOrEmpty(registerTime) && registerTime.Contains(" - "))
                    {
                        string[] registrationTimes = registerTime.Split(new string[] { " - " }, StringSplitOptions.None);
                        DateTime startTime = Convert.ToDateTime(registrationTimes[0]);
                        DateTime endTime = Convert.ToDateTime(registrationTimes[1]);
                        data = data.Where(k => k.registerTime > startTime && k.registerTime < endTime);
                    }
                    count = data.Count();
                    data = data.OrderByDescending(k => k.registerTime).Skip((page - 1) * limit).Take(limit);
                    return data.ToList();
                }
            }
            catch (System.Exception)
            {

                throw;
            }
        }

        #endregion
    }
}
